package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.client.DictFeignClient;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.mapper.HospitalSetMapper;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.HospitalSet;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description:接口实现类
 * @author :又菜又爱玩的→速趴塞亚锦←
 * @create :2023/5/17
 * @param  :1.8
 */
@Service
public class HospitalServiceImpl  implements HospitalService {

    @Resource
    private HospitalRepository hospitalRepository;
    @Resource
    private HospitalSetMapper hospitalSetMapper;//这里是去本地数据库里面查

    /**
     * @description:使用Openfeign一共四步
     *  *        第一步：导入依赖
     *  *        第二步：自定义一个fein客户端接口，@FeinClient(value="调用方在注册中心上的应用名称")，方法和被调用方的controller层方法完全一致
     *  *        第三步：在主启动类上加@EnableFeignClients注解
     *  *        第四步：在远程调用的地方直接注入自定义feign接口的代理类对象，即可远程调用    （下面的就是（注入））
     * @author :又菜又爱玩的→速趴塞亚锦←
     * @create :2023/5/18
     * @param  :1.8
     */
    @Resource
    private DictFeignClient dictFeignClient;//直接是调另一个微服务的接口---==牛逼！==---


    @Override
    public void saveHospital(Map<String, Object> resultMap) {
        //JSONObject阿里巴巴的依赖包
        Hospital hospital = JSONObject.parseObject(JSONObject.toJSONString(resultMap), Hospital.class);
        //转换操作==先转成字符串 =（toJSONString）在转成Hospital对象 =（parseObject）
        String hoscode = hospital.getHoscode();// ↓ 属性名Hospital里面的Hoscode(hoscode)==(不能瞎写)（首字母大写=H）
        Hospital collection = hospitalRepository.findByHoscode(hoscode);

        if(collection == null){//平台上没有该医院信息做添加
            hospital.setStatus(0);//"状态 0：未上线 1：已上线"
            hospital.setCreateTime(new Date());//时间
            hospital.setUpdateTime(new Date());//更新时间
            hospital.setIsDeleted(0);//删除
            hospitalRepository.save(hospital);
        }else{//平台上有该医院信息做修改
            hospital.setStatus(collection.getStatus());
            hospital.setCreateTime(collection.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(collection.getIsDeleted());

            //save = 又能添加也可以修改
            hospital.setId(collection.getId());
            hospitalRepository.save(hospital);
        }


    }

    @Override
    public String getSignKeyWithHoscode(String requestHoscode) {
        QueryWrapper<HospitalSet> hospitalSetQueryWrapper=new QueryWrapper<HospitalSet>();
        hospitalSetQueryWrapper.eq("hoscode", requestHoscode);
        HospitalSet hospitalSet = hospitalSetMapper.selectOne(hospitalSetQueryWrapper);

        if(hospitalSet == null){ //这里调的是自定义异常方法
           throw new YyghException(20001,"该医院信息不存在");
        }
        return hospitalSet.getSignKey();
    }

    /**
     * @description:第三方医院管理的基本信息显示操作
     * @author :又菜又爱玩的→速趴塞亚锦←     根据医院编号查询医院信息
     * @create :2023/5/17
     * @param  :1.8
     */
    @Override
    public Hospital getHospitalByHoscode(String hoscode) {
//  (简化)      Hospital byHoscode = hospitalRepository.findByHoscode(hoscode);
        return hospitalRepository.findByHoscode(hoscode);
    }

    /**
     * @description://带查询条件的医院的分页展示展示
     * @author :又菜又爱玩的→速趴塞亚锦←
     * @create :2023/5/18
     * @param  :1.8
     */
    @Override
    public Page<Hospital> getHospitalPage(Integer pageNum, Integer pageSize, HospitalQueryVo hospitalQueryVo) {

        Hospital hospital=new Hospital();
        if(!StringUtils.isEmpty(hospitalQueryVo.getHosname())){
            hospital.setHosname(hospitalQueryVo.getHosname());
        }
        if(!StringUtils.isEmpty(hospitalQueryVo.getProvinceCode())){
            hospital.setProvinceCode(hospitalQueryVo.getProvinceCode());//*       ****************这三个if是精确查询
        }
        if(!StringUtils.isEmpty(hospitalQueryVo.getCityCode())){
            hospital.setCityCode(hospitalQueryVo.getCityCode());
        }
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                //.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：*******模糊查询
                .withMatcher("hosname", ExampleMatcher.GenericPropertyMatchers.contains())
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        Example<Hospital> of = Example.of(hospital,matcher);


        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by("createTime").ascending());
        Page<Hospital> page = hospitalRepository.findAll(of, pageRequest);//前端下栏的分页信息

        //流的方式                    遍历    朗伯达表达式
        page.getContent().stream().forEach(item->{    //page.getContent().stream()当前页，转换成流对象
            this.packageHospital(item);
        });

        return page;
    }

    /**
     * @description://是医院管理||医院列表里面的=====根据医院id修改医院状态
     * @author :又菜又爱玩的→速趴塞亚锦←
     * @create :2023/5/18
     * @param  :1.8
     */
    @Override
    public void updateStatus(String id, Integer status) {
        if(status == 0 || status == 1){
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    /**
     * @description==============================================://用户端模糊查询
     * @author :又菜又爱玩的→速趴塞亚锦←
     * @create :2023/5/18
     * @param  :1.8
     */
    @Override
    public List<Hospital> findByNameLike(String name) {
        return hospitalRepository.findByHosnameLike(name);
    }

    /**
     * @description:___________________________-——————//用户端点击医院显示详情信息
     * @author :又菜又爱玩的→速趴塞亚锦←
     * @create :2023/5/18
     * @param  :1.8
     */
    @Override
    public Hospital getHospitalDetail(String hoscode) {
        Hospital hospital = hospitalRepository.findByHoscode(hoscode);
        this.packageHospital(hospital);
        return hospital;
    }

    /**
     * @description://是医院管理||医院列表里面的=====(查看)医院详情
     * @author :又菜又爱玩的→速趴塞亚锦←
     * @create :2023/5/18
     * @param  :1.8
     */
    @Override
    public Hospital detail(String id) {
        Hospital hospital = hospitalRepository.findById(id).get();
        this.packageHospital(hospital);
        return hospital;
    }


    //这是一个封装的方法可以有一个快捷键和上面是一起（的带查询条件的医院的分页展示展示）
    private void packageHospital(Hospital hospital){
        String hostype = hospital.getHostype();

        String provinceCode = hospital.getProvinceCode();
        String cityCode = hospital.getCityCode();
        String districtCode = hospital.getDistrictCode();


        String provinceAddress = dictFeignClient.getNameByValue(Long.parseLong(provinceCode));
        String cityAddress = dictFeignClient.getNameByValue(Long.parseLong(cityCode));
        String districtAddress = dictFeignClient.getNameByValue(Long.parseLong(districtCode));

                                                                 //↓ 点一下
        String level = dictFeignClient.getNameByDictCodeAndValue(DictEnum.HOSTYPE.getDictCode(), Long.parseLong(hostype));

        hospital.getParam().put("hostypeString", level);
        hospital.getParam().put("fullAddress", provinceAddress+cityAddress+districtAddress + hospital.getAddress());

    }

}
